package com.xiran.todoself.controller;

import com.xiran.todoself.model.pojo.TodoItem;
import com.xiran.todoself.service.TodoService;
import com.xiran.todoself.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@RestController
@RequestMapping("/api/todo")
@Api(tags = "待办事项")
@Slf4j
public class TodoController {
    @Resource
    private TodoService todoService;
    @Autowired
    private JwtUtils jwtUtils;

    private Long currentUser() {
        String token = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest().getHeader("Authorization");
        log.info("获取当前用户token:{}", token);
        return jwtUtils.getUserId(token);
    }

    @GetMapping
    @ApiOperation("列表")
    public List<TodoItem> list() {
        log.info("开始获取所有事项列表啦");
        return todoService.list(currentUser());
    }

    @PostMapping
    @ApiOperation("新增")
    public TodoItem add(@RequestParam String title) {
        // 1. 创建实体对象并设置 title
        TodoItem todoItem = new TodoItem();
        todoItem.setTitle(title); // 先设置 title（void 方法单独调用）
        todoItem.setUserId(currentUser());
        todoItem.setCreateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        // 2. 调用 Service 层方法（只传实体对象，userId 在 Service 中设置更合理）
        log.info("todo实体对象" + todoItem);
        return todoService.add(todoItem);
    }

    @PatchMapping("/{id}/toggle")
    @ApiOperation("切换完成状态")
    public boolean toggle(@PathVariable Long id) {
        log.info("准备切换id为 {} 任务的状态", id);

        return todoService.toggle(currentUser(), id);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除")
    public boolean delete(@PathVariable Long id) {
        log.info("删除id为 {} 的事务", id);
        return todoService.delete(currentUser(), id);
    }
}
